﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using RaytracerLib.MathLib;
using TomanuExtensions;

namespace Raytracer.PropertyGridDecorators
{
    public class Matrix3Converter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext a_context,
            Type a_source_type)
        {
            if (a_source_type == typeof(string))
                return true;

            return base.CanConvertFrom(a_context, a_source_type);
        }

        public override bool CanConvertTo(ITypeDescriptorContext a_context,
            Type a_destination_type)
        {
            if (a_destination_type == typeof(Vector3))
                return true;

            return base.CanConvertTo(a_context, a_destination_type);
        }

        public override object ConvertFrom(ITypeDescriptorContext a_context,
            CultureInfo a_culture, object a_value)
        {
            if (a_value is string)
            {
                string str = (a_value as string).Replace(") (", ",").Replace("(", "").
                    Replace(")", "");
                var ar = str.Split(new[] { ',' }).Select(
                        s => s.ToDouble()).ToArray();

                var v = new Matrix3(ar);

                return new Matrix3Properties(() => v, (r) => Debug.Fail(""));
            }

            return base.ConvertFrom(a_context, a_culture, a_value);
        }

        public override object ConvertTo(ITypeDescriptorContext a_context,
            CultureInfo a_culture, object a_value, Type a_destination_type)
        {
            if (a_destination_type == typeof(string))
            {
                var v = a_value as Matrix3Properties;
                return v.Getter().ToString();
            }

            return base.ConvertTo(a_context, a_culture, a_value, a_destination_type);
        }

        public override bool GetPropertiesSupported(ITypeDescriptorContext a_context)
        {
            return true;
        }

        public override PropertyDescriptorCollection GetProperties(
            ITypeDescriptorContext a_context, object a_value, Attribute[] a_attributes)
        {
            return TypeDescriptor.GetProperties(a_value, a_attributes);
        }
    }
}